//
//  XDLMLoginViewController.m
//  xindailianmeng
//
//  Created by 许佳奇 on 17/1/17.
//  Copyright © 2017年 xindailianmeng.cn. All rights reserved.
//*******登录页

#import "XDLMLoginViewController.h"
#import "XDLMUIFactory.h"
#import "AFHTTPSessionManager+POST.h"
#import "ZHRTBasicMethod.h"
#import "ZHRTRequestFailureShowViewOrDetail.h"

#import "XDLMRegisteViewController.h"
#import "XDLMRegisterNowViewController.h"
#define TCOLOR [UIColor colorWithRed:187.0/255.0 green:147.0/255.0 blue:115.0/255.0 alpha:1]
@interface XDLMLoginViewController ()<UITextFieldDelegate>
@property (nonatomic, weak) UIImageView *backImgView;

@property (nonatomic, weak) UITextField *phoneNumTF;

@property (nonatomic, weak) UITextField *commendTf;

@property (nonatomic, weak) UIView *lineNoLab;

@property (nonatomic, weak) UIButton *nextBtn;

@property (nonatomic, weak) UIButton *agreeBtn;


@property (nonatomic, copy) NSString *previousTextFieldContent;

@property (nonatomic, assign) BOOL isRegisted;
// 记录上次phoneNumTF输入的
@property (nonatomic, copy) NSString *record;

@end

@implementation XDLMLoginViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    self.phoneNumTF.text = nil;
    self.record = nil;
    self.isRegisted = YES;
    [self.phoneNumTF becomeFirstResponder];
    [self addviews];

}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"输入手机号";

    self.isRegisted = YES;
    
    [self.navigationController.navigationBar setBarTintColor:[UIColor blackColor]];

    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
    
    UIFont *font = [UIFont fontWithName:@"Arial-ItalicMT" size:20];
    NSDictionary *dic = @{NSFontAttributeName:font,
                          NSForegroundColorAttributeName: TCOLOR};
    self.navigationController.navigationBar.titleTextAttributes =dic;

    // 隐藏导航栏
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"nav"] forBarMetrics:UIBarMetricsDefault];
    self.hidesBottomBarWhenPushed = YES;
    // 自定义返回按钮
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"back"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(back)];

    if (self.isTip) {
        [ZHRTRequestFailureShowViewOrDetail showViewDetail:@"您还未登录" view:self.view];
    }
}

- (void)addviews
{
    UIImage *backIma = [UIImage imageNamed:@"login_bg"];
    UIImageView *backImgView = [[UIImageView alloc] initWithImage:backIma];
    backImgView.frame = kScreenB;
    backImgView.userInteractionEnabled = YES;
    self.backImgView = backImgView;
    [self.view addSubview:backImgView];
    
    
    UITextField *phoneNumTF = [self createTextFieldWithFrame:CGRectMake(54, 113 * kscale, kScreenW - 108, 40) textFont:kBaseFont_(22) textColor:TCOLOR placeholder:@"请输入手机号登录或注册" placeholderFont:kBaseFont_(15)  delegate:self inView:backImgView];
    self.phoneNumTF = phoneNumTF;
    self.phoneNumTF.text = self.record;

    //改变clearbutton北京图片
    UIButton *clearButton = [self.phoneNumTF valueForKey:@"_clearButton"];
    [clearButton setImage:[UIImage imageNamed:@"clearbtn"] forState:UIControlStateNormal];
    [clearButton setImage:[UIImage imageNamed:@"clearbtn"] forState:UIControlStateHighlighted];
 
    UILabel *lineLab = [[UILabel alloc] initWithFrame:CGRectMake(54, 153* kscale, kScreenW - 108, 1)];
    lineLab.backgroundColor = TCOLOR;
    [backImgView addSubview:lineLab];
    
    if (!self.isRegisted) {
        
        self.phoneNumTF.clearButtonMode = UITextFieldViewModeAlways;
        
        UITextField *commendTf = [self createTextFieldWithFrame:CGRectMake(54, 153* kscale, kScreenW - 108, 40) textFont:kBaseFont_(22) textColor:TCOLOR placeholder:@"请输入正确推荐码(选填)" placeholderFont:kBaseFont_(15)  delegate:self inView:backImgView];
        self.commendTf = commendTf;
        self.commendTf.keyboardType = UIKeyboardTypeDefault;
        //改变clearbutton北京图片
        UIButton *clearButton = [self.commendTf valueForKey:@"_clearButton"];
        [clearButton setImage:[UIImage imageNamed:@"clearbtn"] forState:UIControlStateNormal];
        [clearButton setImage:[UIImage imageNamed:@"clearbtn"] forState:UIControlStateHighlighted];
        
        UILabel *lineNoLab = [[UILabel alloc] initWithFrame:CGRectMake(54, 193* kscale, kScreenW - 108, 1)];
        lineNoLab.backgroundColor = TCOLOR;
        self.lineNoLab = lineNoLab;
        [backImgView addSubview:lineNoLab];
    } else {
        
        self.commendTf = nil;
        [self.commendTf removeFromSuperview];
        [self.lineNoLab removeFromSuperview];
        
    }
    CGFloat nextBtnY = self.isRegisted ? 200 * kscale : 240 * kscale;
    //下一步按钮
    UIButton *nextBtn = [[UIButton alloc] initWithFrame:CGRectMake(54, nextBtnY, kScreenW - 108, 50*kscale)];
    [nextBtn setBackgroundImage:[UIImage imageNamed:@"nextone"] forState:UIControlStateDisabled];
    [nextBtn setBackgroundImage:[UIImage imageNamed:@"next"] forState:UIControlStateNormal];
    [nextBtn addTarget:self action:@selector(NextBtnClick) forControlEvents:UIControlEventTouchUpInside];
    nextBtn.enabled = NO;
    self.nextBtn = nextBtn;
    [backImgView addSubview:nextBtn];
    
    UIView *dowmView = [[UIView alloc] initWithFrame:CGRectMake(65*kscale, CGRectGetMaxY(nextBtn.frame) + 20, kScreenW - 130, 16)];
    [backImgView addSubview:dowmView];
    
    UIButton *agreeBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 2, 12, 12)];
    [agreeBtn setBackgroundImage:[UIImage imageNamed:@"agree_yes"] forState:UIControlStateSelected];
    [agreeBtn setBackgroundImage:[UIImage imageNamed:@"agree_nor"] forState:UIControlStateNormal];
    agreeBtn.selected = YES;
    [agreeBtn addTarget:self action:@selector(agreeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    self.agreeBtn = agreeBtn;
    [dowmView addSubview:agreeBtn];
    
    UILabel *alreadyReadLab = [[UILabel alloc] initWithFrame:CGRectMake(16*kscale, 0, 90*kscale, 12)];
    alreadyReadLab.text = @"我已阅读并同意";
    alreadyReadLab.adjustsFontSizeToFitWidth = YES;
    alreadyReadLab.textColor = [UIColor grayColor];
    [dowmView addSubview:alreadyReadLab];
    
    UIButton *xindaiBtn = [[UIButton alloc] initWithFrame:CGRectMake(98*kscale, 2, 150*kscale, 12)];
    xindaiBtn.titleLabel.font = [UIFont systemFontOfSize:FONTSIZE12];
    [xindaiBtn setTitle:@"《新贷联盟用户注册协议》" forState:UIControlStateNormal];
    [xindaiBtn setTitleColor:TCOLOR forState:UIControlStateNormal];
    [xindaiBtn addTarget:self action:@selector(xindaiBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [dowmView addSubview:xindaiBtn];
    
    UILabel *goalLab = [[UILabel alloc] initWithFrame:CGRectMake(0, kScreenH - 150, kScreenW, 60)];
    goalLab.textColor = TCOLOR;
    goalLab.text = @"定一个小目标，先赚他一个亿";
    goalLab.font = [UIFont systemFontOfSize:FONTSIZE18];
    goalLab.textAlignment = NSTextAlignmentCenter;
    [backImgView addSubview:goalLab];
}
//请求数据
- (void)loadData
{
    NSString *text = [self.phoneNumTF.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    self.record = self.phoneNumTF.text;
    NSDictionary *param = @{@"method":@"verifyMobile",@"mobile":text};
    [AFHTTPSessionManager POSTWithParams:param success:^(NSURLSessionDataTask *task, id responseObject) {

        if ([responseObject[@"code"] isEqualToString:@"100000"]) {
            NSLog(@"%@",responseObject[@"result"][@"registed"]);
            if ([responseObject[@"result"][@"registed"] isEqualToString:@"Y"]) {
                self.isRegisted = YES;
                [self.backImgView removeFromSuperview];
                [self addviews];
                self.nextBtn.enabled = YES;
            }
            else
            {
                self.isRegisted = NO;
                [self.backImgView removeFromSuperview];
                [self addviews];
                self.nextBtn.enabled = YES;
                
            }
        } else {
            
            [ZHRTRequestFailureShowViewOrDetail showViewDetail:responseObject[@"message"] view:self.view];
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
    
   
    
}


- (UITextField *)createTextFieldWithFrame:(CGRect)frame textFont:(UIFont *)textFont textColor:(UIColor *)textColor placeholder:(NSString *)placeholder placeholderFont:(UIFont *)placeholderFont delegate:(id)obj inView:(UIView *)inView  {
    
    UITextField *textField = [[UITextField alloc] initWithFrame:frame];
    textField.textColor =  textColor;
    textField.font = textFont;
    textField.attributedPlaceholder = [self textFieldAttributedPlaceholderWith:textField placeholder:placeholder placeholderFont:placeholderFont];
    textField.keyboardType = UIKeyboardTypeNumberPad;
    textField.delegate = self;
    [textField addTarget:self action:@selector(numberChange:) forControlEvents:UIControlEventEditingChanged];
//    textField.clearsOnBeginEditing = YES;
    textField.clearButtonMode = UITextFieldViewModeWhileEditing;
//        UIButton *clearBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 1, 15, 48)];
//        self.clearBtn = clearBtn;
//        clearBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
//        clearBtn.contentEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
//        [clearBtn addTarget:self action:@selector(clearBtnClick) forControlEvents:UIControlEventTouchUpInside];
//        clearBtn.enabled = NO;
//        textField.rightView = clearBtn;
//    textField.rightViewMode = UITextFieldViewModeAlways;
    [inView addSubview:textField];
    return textField;
}

//修改UITextField的placeholder字体并垂直居中
- (NSAttributedString *)textFieldAttributedPlaceholderWith:(UITextField *)textField placeholder:(NSString *)placeholder placeholderFont:(UIFont *)placeholderFont  {
    if (placeholder) {
        NSMutableParagraphStyle *style = [textField.defaultTextAttributes[NSParagraphStyleAttributeName] mutableCopy];
        style.minimumLineHeight = textField.font.lineHeight - (textField.font.lineHeight - placeholderFont.lineHeight) / 2.0;
        NSAttributedString *attr = [[NSAttributedString alloc] initWithString:placeholder attributes:@{
                                                                                                       NSFontAttributeName:placeholderFont, NSParagraphStyleAttributeName : style,
                                                                                                       
                                                                                                       NSForegroundColorAttributeName:TCOLOR
 
 }];
        return attr;
    }
    return nil;
}

#pragma mark -- 点击方法
//点击下一步按钮
- (void)NextBtnClick
{
    NSLog(@"下一步按钮");
    XDLMRegisteViewController *registerCtr = [[XDLMRegisteViewController alloc] init];
    registerCtr.phoneNumber = self.phoneNumTF.text;
    registerCtr.textCode = self.commendTf.text ? self.commendTf.text : @"";
    registerCtr.isLoginCome =  self.isRegisted;
    [self.navigationController pushViewController:registerCtr animated:YES];
}

// 同意图标的点击
- (void)agreeBtnClick:(UIButton *)agreeBtn {
    
    agreeBtn.selected = !agreeBtn.selected;
     NSString *text = [self.phoneNumTF.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    if ([ZHRTBasicMethod isMobileNumber:text]) {
 
            self.nextBtn.enabled = agreeBtn.selected;
            

    }
    
}

- (void)xindaiBtnClick {
    
    
    NSLog(@"《新贷联盟用户注册协议》");
    
}

//监听输入框值变化
- (void)numberChange:(UITextField *)textField
{
    if (textField == self.phoneNumTF) {
        self.phoneNumTF.clearButtonMode = UITextFieldViewModeWhileEditing;
        //限制手机账号长度（有两个空格）
        if (textField.text.length > 13) {
            textField.text = [textField.text substringToIndex:13];
        }
        
        NSUInteger targetCursorPosition = [textField offsetFromPosition:textField.beginningOfDocument toPosition:textField.selectedTextRange.start];
        
        NSString *currentStr = [textField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
        NSString *preStr = [self.previousTextFieldContent stringByReplacingOccurrencesOfString:@" " withString:@""];
        
        //正在执行删除操作时为0，否则为1
        char editFlag = 0;
        if (currentStr.length <= preStr.length) {
            editFlag = 0;
        }
        else {
            editFlag = 1;
        }
        
        NSMutableString *tempStr = [NSMutableString new];
        
        int spaceCount = 0;
        if (currentStr.length < 3 && currentStr.length > -1) {
            spaceCount = 0;
        }else if (currentStr.length < 7 && currentStr.length > 2) {
            spaceCount = 1;
        }else if (currentStr.length < 12 && currentStr.length > 6) {
            spaceCount = 2;
        }
        
        for (int i = 0; i < spaceCount; i++) {
            if (i == 0) {
                [tempStr appendFormat:@"%@%@", [currentStr substringWithRange:NSMakeRange(0, 3)], @" "];
            }else if (i == 1) {
                [tempStr appendFormat:@"%@%@", [currentStr substringWithRange:NSMakeRange(3, 4)], @" "];
            }else if (i == 2) {
                [tempStr appendFormat:@"%@%@", [currentStr substringWithRange:NSMakeRange(7, 4)], @" "];
            }
        }
        
        if (currentStr.length == 11) {
            [tempStr appendFormat:@"%@%@", [currentStr substringWithRange:NSMakeRange(7, 4)], @" "];
        }
        if (currentStr.length < 4) {
            [tempStr appendString:[currentStr substringWithRange:NSMakeRange(currentStr.length - currentStr.length % 3, currentStr.length % 3)]];
        }else if(currentStr.length > 3 && currentStr.length <12) {
            NSString *str = [currentStr substringFromIndex:3];
            [tempStr appendString:[str substringWithRange:NSMakeRange(str.length - str.length % 4, str.length % 4)]];
            if (currentStr.length == 11) {
                [tempStr deleteCharactersInRange:NSMakeRange(13, 1)];
            }
        }
        textField.text = tempStr;
        // 当前光标的偏移位置
        NSUInteger curTargetCursorPosition = targetCursorPosition;
        
        if (editFlag == 0) {
            //删除
            if (targetCursorPosition == 9 || targetCursorPosition == 4) {
                curTargetCursorPosition = targetCursorPosition - 1;
            }
        }else {
            //添加
            if (currentStr.length == 8 || currentStr.length == 4) {
                curTargetCursorPosition = targetCursorPosition + 1;
            }
        }
        UITextPosition *targetPosition = [textField positionFromPosition:[textField beginningOfDocument] offset:curTargetCursorPosition];  
        [textField setSelectedTextRange:[textField textRangeFromPosition:targetPosition toPosition :targetPosition]];
    
    //判断是否是手机号码
    NSString * phone =  [textField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    if ([ZHRTBasicMethod isMobileNumber:phone]) {
        
            [self loadData];
        self.nextBtn.enabled = YES;
    }else {
        
        self.nextBtn.enabled = NO;
        if (phone.length == 11) {
            
            [ZHRTRequestFailureShowViewOrDetail showViewDetail:@"请输入正确手机号" view:self.view];
        }
    }
    }
    
}
#pragma mark -- UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField == self.phoneNumTF) {
        
        self.previousTextFieldContent = textField.text;
    }
    return YES;
}
#pragma mark -- 辅助方法
//点击空白区域，隐藏键盘
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    //结束编辑
    [self.view endEditing:YES];
}

- (void)back {
    
    NSUserDefaults *df = [NSUserDefaults standardUserDefaults];
    
    [df removeObjectForKey:@"isMine"];
    
    [df synchronize];
    

  
    // 判断两种情况: push 和 present
    if ((self.presentedViewController || self.presentingViewController) && self.childViewControllers.count == 1) {
        [self dismissViewControllerAnimated:YES completion:nil];
    } else{
     [self dismissViewControllerAnimated:YES completion:nil];
//        [self.navigationController popViewControllerAnimated:YES];
        UITabBarController *tab = (UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
        tab.selectedIndex = 0;
    }
}

@end
